using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Adex;
using MediaMonitor.Common;
using System.Net;
using System.Data;
using System.Text;

namespace MediaMonitor
{
    public partial class Login : Adex.BasePage
    {

        protected void page_load(Object sender, EventArgs e)
        {
            if (!IsPostBack)
            {


                string retUrl = null;
                retUrl = Utility.GetRequestedVal("ReturnUrl", "");

                HyperLink lnkReg = this.loginx.FindControl("lnkReg") as HyperLink;
                string heading = null;
                if (!string.IsNullOrEmpty(retUrl))
                {
                    if (retUrl.Contains("/users/"))
                    {
                        heading = "User's login required";
                        if ((lnkReg != null))
                            lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=3&returnUrl=" + retUrl;
                    }
                    else if (retUrl.Contains("/client/"))
                    {
                        heading = "Company's login required";
                        if ((lnkReg != null))
                            lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=2&returnUrl=" + retUrl;
                    }
                    else if (retUrl.Contains("/admin/"))
                    {
                        heading = "Admin's login required";
                        if ((lnkReg != null))
                            lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=1&returnUrl=" + retUrl;
                    }
                    else
                    {
                        heading = "User's login required";
                        if ((lnkReg != null))
                            lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=3&returnUrl=" + retUrl;
                    }
                }
                else
                {
                    heading = "User's login required";
                    if ((lnkReg != null))
                        lnkReg.NavigateUrl = Utility.AppPath + "/register.aspx?type=3&returnUrl=" + retUrl;
                }

                this.ltrHeading.Text = heading;

            }

        }

        protected void login_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
        {
           




             string userName = loginx.UserName;
        string password = loginx.Password;
        bool rememberUserName = loginx.RememberMeSet;
            ReportFuncs rep = new ReportFuncs();
            Int32 UserID = 0; Boolean IsLoggedIn;
             MembershipUser user = Membership.GetUser(loginx.UserName);
            // if (user != null && user.LastPasswordChangedDate.Date.AddDays(90) < DateTime.Now.Date && loginx.UserName.ToLower() != "admin")
             //{
               //  string script = "alert(\"Your password has expired, please contact AGB Team to set a new one!\");";
               //  ScriptManager.RegisterStartupScript(this, this.GetType(), "ServerControlScript", script, true);
             //}
             //else
             //{

                 if (System.Web.Security.Membership.ValidateUser(loginx.UserName, loginx.Password))
                 {
                     FormsAuthenticationTicket tktAuthenticatedUser = default(FormsAuthenticationTicket);
                     string sCookie = null;
                     HttpCookie hckHttpCookie = default(HttpCookie);

                     tktAuthenticatedUser = new FormsAuthenticationTicket(loginx.UserName, true, 50000);
                     sCookie = FormsAuthentication.Encrypt(tktAuthenticatedUser);
                     hckHttpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, sCookie);
                     hckHttpCookie.Expires = DateTime.Now.AddYears(1);
                     Response.Cookies.Add(hckHttpCookie);


                     FormsAuthentication.RedirectFromLoginPage(loginx.UserName, true);

                     SiteUser usr = AppUser.GetUserByUserName(loginx.UserName);

                     AppUser.SignIn(usr.SiteUserID, loginx.RememberMeSet);
                     UserID = usr.SiteUserID;
                     Session["UserID"] = UserID;
                     Session["Company"] = usr.Company;
                     Session["Name"] = usr.FullName;
                     Session["CompanyCode"] = usr.CompanyCode;
                     DataTable dt = rep.GetUserIDAndRolle(Session["UserID"].ToString());
                     Session["UserRole"] = dt.Rows[0][2].ToString();
                     HttpCookie NoSummary = new HttpCookie("NoSummary");
                     NoSummary.Value = GetCompanyNoSummary(Convert.ToInt32(usr.CompanyCode));
                     NoSummary.Expires = DateTime.Now.AddYears(1);
                     Response.Cookies.Add(NoSummary);
                     Response.Cookies["User"]["UserID"] = UserID.ToString();
                     Response.Cookies["User"]["Company"] = usr.Company.ToString();
                     Response.Cookies["User"]["Name"] = usr.FullName;
                     Response.Cookies["User"]["CompanyCode"] = usr.CompanyCode.ToString();
                     Response.Cookies["User"]["UserRole"] = dt.Rows[0][2].ToString();
                     Response.Cookies["User"]["UserName"] = usr.UserName;
                     Response.Cookies["User"].Expires = DateTime.Now.AddYears(1);
                     GetEmailApp();
                     FormsAuthentication.SetAuthCookie(loginx.UserName, true);
                     // Create forms authentication ticket
                     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                     1, // Ticket version
                     userName,// Username to be associated with this ticket
                     DateTime.Now, // Date/time ticket was issued
                     DateTime.Now.AddMinutes(50), // Date and time the cookie will expire
                     rememberUserName, // if user has chcked rememebr me then create persistent cookie
                      Session["UserRole"].ToString(), // store the user data, in this case roles of the user
                     FormsAuthentication.FormsCookiePath); // Cookie path specified in the web.config file in <Forms> tag if any.

                     // To give more security it is suggested to hash it
                     string hashCookies = FormsAuthentication.Encrypt(ticket);
                     HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); // Hashed ticket

                     // Add the cookie to the response, user browser
                     Response.Cookies.Add(cookie);
                     IsLoggedIn = Convert.ToBoolean(usr.IsLoggedIn);
                     //if (IsLoggedIn == true)
                     //{
                     //    AjaxFuncs.MsgBox(this.Page,
                     //                        "You are alredy LoggedIn in some another browser on the same Machine or may be on some another Machine.Please Logout from there and try again.");
                     //    return;
                     //}
                     //else
                     //{
                     if (Request.QueryString["ReturnUrl"] != null)
                     {
                         FormsAuthentication.RedirectFromLoginPage(loginx.UserName, true);
                     }
                     if ((Request["ReturnUrl"] != null))
                     {
                         String Val = Server.UrlDecode(Request["ReturnUrl"]).ToString();

                         if (Val.Contains("users") || Val.Contains("Users"))
                         {
                             if (UserID > 0)
                             {
                                 SaveLoginUserDetails(UserID);
                             }

                         }

                         SqlDataSource1.UpdateParameters.Add("SiteUserID", UserID.ToString());
                         SqlDataSource1.Update();
                         //if (HttpContext.Current.Session["RoleName"].ToString() == "advanced user")
                         //    Response.Redirect("~/admin/default.aspx");
                         //else
                         //Response.Redirect(Server.UrlDecode(Request["ReturnUrl"]));
                         Response.Redirect(Request["ReturnUrl"]);
                     }
                     else
                     {
                         if (UserID > 0)
                         {
                             SaveLoginUserDetails(UserID);
                         }
                         Response.Redirect("~/users/defaultnew.aspx");
                     }
                     //SqlDataSource1.UpdateParameters.Add("SiteUserID", UserID.ToString());
                     //SqlDataSource1.Update();
                 }
                 //else {


                     //}

                     // }

                 else
                 {
                     AjaxFuncs.LoginScreen(this.Page, true);
                 }
             //}
        }

        private void SaveLoginUserDetails(Int32 UserID)
        {
            String stringIpAddress = String.Empty;

            //Get IP Address
            stringIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (stringIpAddress == null) //may be the HTTP_X_FORWARDED_FOR is null
            {
                stringIpAddress = Request.ServerVariables["REMOTE_ADDR"];//we can use REMOTE_ADDR
            }

            if (!String.IsNullOrEmpty(stringIpAddress))
            {
                RfController.SiteUser_Insert(UserID, stringIpAddress);
            }
        }
        private string  GetCompanyNoSummary(int companyCode)
        {
            string Nosumary = (SPs.GetCompanyNoSummary(companyCode).ExecuteScalar()).ToString();
            return Nosumary;
        
        }
        private void GetEmailApp()
        {
            DataTable dt = SPs.GetAllEmailPassword("", "").GetDataSet().Tables[0];
            if (dt.Rows.Count > 0)
            {
                string code = dt.Rows[0]["Password"].ToString();
                Response.Cookies["App"]["Email"] = dt.Rows[0]["Email"].ToString();
                string strmsg = string.Empty;
                byte[] encode = new byte[code.Length];
                encode = Encoding.UTF8.GetBytes(code);
                strmsg = Convert.ToBase64String(encode);
                Response.Cookies["App"]["Password"] = strmsg;
                Response.Cookies["App"].Expires = DateTime.Now.AddYears(1);
            }
        }

    }//end class
}
